//
//  FeedTableViewCell.m
//  HejintaoDemo
//
//  Created by jintao he on 2018/11/14.
//  Copyright © 2018 jintao he. All rights reserved.
//

#import "FeedTableViewCell.h"

#import "PRTimelineMaster.h"
#import "HJTButton.h"

// ********************* 自定义参数区 *********************
const CGFloat kTopHintView_Height = 24;
const CGFloat kTopViewMargin_Top = 20;
const CGFloat kTopViewHeight = 40;
const CGFloat kSinkViewMargin_Top = 12;

const CGFloat kSummaryPadding_Left = 20;

const CGFloat kSinkViewMargin_Botoom = 12;
const CGFloat kBottomViewHeight = 50 + 40;
const CGFloat kConatinerMargin_Bottom = 12;
const CGFloat kComponentsHeight = kTopViewMargin_Top+kTopViewHeight+kSinkViewMargin_Top+kSinkViewMargin_Botoom+kBottomViewHeight+kConatinerMargin_Bottom;
const CGFloat kTitleViewMaxHeight = 60.f;
const CGFloat kSummaryPaddingTop = 11;
const CGFloat kContainerMargin_Left = 0;
const CGFloat kSinkMargin_Left = 0;
const CGFloat kTitleLineSpacing = 8;
const CGFloat kSummaryLineSpacing = 8;

#define kVideoViewRatio (455.f/375)

#define kArticleViewHeight (kScreenWidth * (9/16.f))

const CGFloat kImageViewPadding = 5;
const CGFloat kTitlePadding = 12;
const CGFloat kBottomSrcHintView_Height = 20;
const CGFloat kTitleOneLineHeight = 20;


@interface FeedTableViewCell ()

@property (nonatomic, strong) FeedModel *postData;
@property (nonatomic, strong) UIView *containerView;

@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UIButton *columnAvatar;
@property (nonatomic, strong) UILabel *authorLabel;
@property (nonatomic, strong) UILabel *timeLabel;

//bottomView
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) HJTButton *shareBtn;
@property (nonatomic, strong) HJTButton *commentBtn;
@property (nonatomic, strong) HJTButton *likeBtn;
@property (nonatomic, strong) CALayer *sepline;

@property (nonatomic, strong) UIView *leftSeperateLine;
@property (nonatomic, strong) UIView *rightSeperateLine;

@property (nonatomic, strong) UIView *bottomHintView;
@property (nonatomic, strong) HJTButton *locationBtn;
@property (nonatomic, strong) HJTButton *viewBtn;

//context
@property (nonatomic, strong) UIView *sinkView;
@property (nonatomic, strong) UILabel *titleLabel;

@end

@implementation FeedTableViewCell

// ****************** topView lazy ******************

-(UIView *)topView{
    if (!_topView) {
        _topView = [[UIView alloc] init];
    }
    return _topView;
}

-(UIButton *)columnAvatar{
    if (!_columnAvatar) {
        _columnAvatar = [UIButton buttonWithType:UIButtonTypeCustom];
        _columnAvatar.backgroundColor = RGB(245, 245, 245);
        _columnAvatar.layer.cornerRadius = 16;
        _columnAvatar.layer.masksToBounds = YES;
    }
    return _columnAvatar;
}

-(UILabel *)authorLabel{
    if (!_authorLabel) {
        _authorLabel = [UILabel new];
        _authorLabel.font = APPFont(14);
        _authorLabel.textColor = RGB(75, 73, 69);
    }
    return _authorLabel;
}

-(UILabel *)timeLabel{
    if (!_timeLabel) {
        _timeLabel = [UILabel new];
        _timeLabel.font = APPFont(12);
        _timeLabel.textColor = RGB(188, 188, 188);
    }
    return _timeLabel;
}

-(UIView *)bottomHintView{
    if (!_bottomHintView) {
        _bottomHintView = [[UIView alloc] init];
        _bottomHintView.backgroundColor = [UIColor whiteColor];
    }
    return _bottomHintView;
}

// ****************** CommonBottomView lazy ******************

-(UIView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[UIView alloc] init];
        _bottomView.clipsToBounds = YES;
    }
    return _bottomView;
}

-(UIView *)leftSeperateLine{
    if (!_leftSeperateLine) {
        _leftSeperateLine = [[UIView alloc] init];
        _leftSeperateLine.backgroundColor = RGB(245, 245, 245);
        _leftSeperateLine.hidden = YES;
    }
    return _leftSeperateLine;
}

-(UIView *)rightSeperateLine{
    if (!_rightSeperateLine) {
        _rightSeperateLine = [[UIView alloc] init];
        _rightSeperateLine.backgroundColor = RGB(245, 245, 245);
        _rightSeperateLine.hidden = YES;
    }
    return _rightSeperateLine;
}

-(CALayer *)sepline{
    if (!_sepline) {
        _sepline = [CALayer layer];
        _sepline.backgroundColor = RGB(245, 245, 245).CGColor;
        _sepline.frame = CGRectMake(0,40,kScreenWidth,0.5);
    }
    return _sepline;
}


-(HJTButton *)shareBtn{
    if (!_shareBtn) {
        _shareBtn = [[HJTButton alloc] init];
        [_shareBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        _shareBtn.titleLabel.font = APPFont(12);
        [_shareBtn setTitle:@"转发" forState:UIControlStateNormal];
        [_shareBtn setImage:[UIImage imageNamed:@"bottom_share"] forState:UIControlStateNormal];
        _shareBtn.imagePosition = HJTButtonImagePositionLeft;
    }
    return _shareBtn;
}

-(HJTButton *)commentBtn{
    if (!_commentBtn) {
        _commentBtn = [[HJTButton alloc] init];
        [_commentBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        _commentBtn.titleLabel.font = APPFont(12);
        [_commentBtn setTitle:@"评论" forState:UIControlStateNormal];
        _commentBtn.imagePosition = HJTButtonImagePositionLeft;
    }
    return _commentBtn;
}

-(HJTButton *)likeBtn{
    if (!_likeBtn) {
        _likeBtn = [[HJTButton alloc] init];
        [_likeBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        _likeBtn.titleLabel.font = APPFont(12);
        [_likeBtn setTitle:@"点赞" forState:UIControlStateNormal];
        [_likeBtn setImage:[UIImage imageNamed:@"comment_cell_like_n"] forState:UIControlStateNormal];
        _likeBtn.imagePosition = HJTButtonImagePositionLeft;
        _likeBtn.hidden = YES;
    }
    return _likeBtn;
}

-(HJTButton *)locationBtn{
    if (!_locationBtn) {
        _locationBtn = [[HJTButton alloc] init];
        [_locationBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        _locationBtn.titleLabel.font = APPFont(12);
        [_locationBtn setImage:[UIImage imageNamed:@"location_icon"] forState:UIControlStateNormal];
        _locationBtn.imagePosition = HJTButtonImagePositionLeft;
    }
    return _locationBtn;
}

-(HJTButton *)viewBtn{
    if (!_viewBtn) {
        _viewBtn = [[HJTButton alloc] init];
        [_viewBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        _viewBtn.titleLabel.font = APPFont(12);
        [_viewBtn setImage:[UIImage imageNamed:@"ic_discover"] forState:UIControlStateNormal];
        _viewBtn.imagePosition = HJTButtonImagePositionLeft;
    }
    return _viewBtn;
}


// ****************** contentView lazy ******************

-(UIView *)containerView{
    if (!_containerView) {
        _containerView = [[UIView alloc] init];
        _containerView.backgroundColor = [UIColor whiteColor];
    }
    return _containerView;
}

-(UIView *)sinkView{
    if (!_sinkView) {
        _sinkView = [[UIView alloc] init];
    }
    return _sinkView;
}

-(void)configTopView{
    
    [self.containerView addSubview:self.topView];
    [self.topView addSubview:self.columnAvatar];
    [self.topView addSubview:self.authorLabel];
    [self.topView addSubview:self.timeLabel];
    
    [_topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(0);
        make.right.offset(0);
        make.top.offset(kTopViewMargin_Top);
        make.height.mas_equalTo(kTopViewHeight);
    }];
    
    [_columnAvatar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.topView);
        make.left.equalTo(self.topView.mas_left).offset(12);
        make.size.mas_equalTo(CGSizeMake(32, 32));
    }];
    
    [_authorLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.columnAvatar.mas_right).offset(8);
        make.top.equalTo(self.columnAvatar.mas_top);
    }];
    
    [_timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.authorLabel.mas_bottom).offset(2);
        make.left.equalTo(self.authorLabel.mas_left);
    }];
}

-(void)configCommonBottomView{
    
    [self.containerView addSubview:self.bottomView];
    [self.bottomView.layer addSublayer:self.sepline];
    [self.bottomView addSubview:self.shareBtn];
    [self.bottomView addSubview:self.commentBtn];
    [self.bottomView addSubview:self.likeBtn];
    [self.bottomView addSubview:self.bottomHintView];
    
    [self.bottomView addSubview:self.leftSeperateLine];
    [self.bottomView addSubview:self.rightSeperateLine];
    
    [self.bottomHintView addSubview:self.locationBtn];
    [self.bottomHintView addSubview:self.viewBtn];
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.containerView);
        make.bottom.equalTo(self.containerView);
        make.height.mas_equalTo(kBottomViewHeight).priorityHigh();
    }];
    
    [self.bottomHintView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.sinkView);
        make.top.equalTo(self.bottomView);
        make.height.equalTo(@40);
    }];
    
    [self.locationBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.bottomHintView.mas_left).offset(12);
        make.centerY.equalTo(self.bottomHintView);
    }];
    
    [self.viewBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.bottomHintView.mas_right).offset(-12);
        make.centerY.equalTo(self.locationBtn);
    }];
}

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
        self.contentView.backgroundColor = [UIColor clearColor];
        self.backgroundColor = [UIColor whiteColor];
        
        [self configContainViewUI];
    }
    return self;
}

/*
 contentView configuration
 */
- (void)configContainViewUI{
    
    [self.contentView addSubview:self.containerView];
    [self.containerView addSubview:self.sinkView];
    
    [self configTopView];
    
    [self configCommonBottomView];
    
    [self.containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, kConatinerMargin_Bottom, 0));
    }];
    
    [self.sinkView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topView.mas_bottom).offset(kSinkViewMargin_Top);
        make.bottom.equalTo(self.bottomView.mas_top).offset(-kSinkViewMargin_Botoom);
        make.left.right.equalTo(self.topView);
    }];
    
}

/*
 image configuration
 */
-(void)configImagePost{
    W_SELF
    _titleLabel = [UILabel new];
    _titleLabel.font = APPFont(16);
    _titleLabel.textColor = RGB(75, 73, 69);
    _titleLabel.numberOfLines = 3;
    _titleLabel.preferredMaxLayoutWidth = kScreenWidth - kSummaryPadding_Left*2;
    _titleLabel.textAlignment = NSTextAlignmentLeft;
    
    [self.sinkView addSubview:self.titleLabel];
    
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.sinkView);
        make.left.offset(kSummaryPadding_Left);
        make.right.offset(-kSummaryPadding_Left);
        make.height.equalTo(@([FeedTableViewCell heightForSummary:weakSelf.postData.topic]));
    }];
    
    CGFloat paddingTop = _postData.topic.length == 0 ? 0 : kTitlePadding;
    
    _imagesView = [UIView new];
    [self.sinkView addSubview:_imagesView];
    [_imagesView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLabel.mas_bottom).offset(paddingTop);
        make.bottom.equalTo(self.sinkView);
        make.left.offset(kSummaryPadding_Left);
        make.right.offset(-kSummaryPadding_Left);
    }];
    
    _titleLabel.text = _postData.topic;
}

/*
 article configuration
 */
-(void)configArticlePost{
    W_SELF
    _titleLabel = [UILabel new];
    _titleLabel.font = APPFont(16);
    _titleLabel.textColor = [UIColor blackColor];
    _titleLabel.numberOfLines = 3;
    _titleLabel.preferredMaxLayoutWidth = kScreenWidth - kSummaryPadding_Left*2;
    _titleLabel.textAlignment = NSTextAlignmentLeft;
    [self.sinkView addSubview:_titleLabel];
    
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(kSummaryPadding_Left);
        make.right.offset(-kSummaryPadding_Left);
        make.top.equalTo(self.sinkView);
        make.height.mas_equalTo([FeedTableViewCell heightForSummary:weakSelf.postData.topic]);
    }];
    
    if (_postData.tags.count > 0) {
        
        NSMutableAttributedString *labelStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@" %@",_postData.topic]];
        NSTextAttachment *attch = [[NSTextAttachment alloc] init];
        attch.image = [UIImage imageNamed:@"ding_icon"];
        attch.bounds = CGRectMake(0, -2, 16, 16);
        NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
        
        [labelStr insertAttributedString:string atIndex:0];
        _titleLabel.attributedText = labelStr;
    }else{
        _titleLabel.text = _postData.topic;
    }
    
}

/** 计算文字高度  */
+(CGFloat)heightForSummary:(NSString *)summary{
    if (summary.length == 0) {
        return 0;
    }
    
    NSMutableParagraphStyle *pstyle = [NSMutableParagraphStyle new];
    pstyle.lineSpacing = kSummaryLineSpacing;
    
    NSDictionary *attr = @{NSFontAttributeName : APPFont(16),
                           NSParagraphStyleAttributeName : pstyle
                           };
    
    CGRect rect = [summary boundingRectWithSize:CGSizeMake(kScreenWidth-kSinkMargin_Left*2-kContainerMargin_Left*2, HUGE)
                                        options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                     attributes:attr context:nil];
    
    return ceil(rect.size.height)+1;
}

/** cell 高度  */
+(CGFloat)cellHeightForType:(FeedModel *)pdata{
    CGFloat contentHeight = kComponentsHeight;
    
    if ([pdata.type isEqualToString:@"normal"]){
        
        CGFloat height = [FeedTableViewCell heightForSummary:pdata.topic];
        
        CGFloat textH = height;
        
        contentHeight = kComponentsHeight + textH + (textH > 0 ? kTitlePadding : 0) + [FeedTableViewCell heightForImages: pdata.images];
        
        
    }else if ([pdata.type isEqualToString:@"question"]){
        CGFloat lineHeight = [FeedTableViewCell heightForSummary:pdata.topic];
        
        contentHeight = kComponentsHeight + lineHeight;
    }
    
    return contentHeight;
}

-(void)renderAuthor{
    
    [_columnAvatar mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.topView);
        make.left.equalTo(self.topView.mas_left).offset(12);
        make.size.mas_equalTo(CGSizeMake(32, 32));
    }];
    
    _authorLabel.text = _postData.userName;
    
}

-(void)setPostData:(FeedModel *)postData{
    _postData = postData;
    
    [self renderAuthor];
    
    CGFloat time = [postData.createTime floatValue] / 1000.0;
    
    self.timeLabel.text = [PRTimelineMaster dateForFormatOneWithTimeStamp:[NSString stringWithFormat:@"%.f",time]];
    
    [_topView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.offset(kTopViewMargin_Top);
    }];
    [_bottomView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(kBottomViewHeight).priorityHigh();
    }];
    
    [self.sinkView removeAllSubviews];
    
    if ([postData.type isEqualToString:@"question"]){
        
        [self configArticlePost];
        
        
    }else if ([postData.type isEqualToString:@"normal"]){
        
        [self configImagePost];
        
        [FeedTableViewCell createImageViewsForView:_imagesView
                                 byPostData:_postData];
    }
    
    [self.locationBtn setTitle:[NSString stringWithFormat:@"%@",postData.address] forState:UIControlStateNormal];
    [self.viewBtn setTitle:[NSString stringWithFormat:@" %@",postData.viewCount] forState:UIControlStateNormal];
    
    if ([postData.type isEqualToString:@"normal"]) {
        
        self.likeBtn.hidden = NO;
        self.leftSeperateLine.hidden = NO;
        self.rightSeperateLine.hidden = NO;
        
        [self.shareBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.equalTo(self.bottomView);
            make.top.equalTo(self.bottomHintView.mas_bottom);
            make.right.equalTo(self.commentBtn.mas_left);
        }];
        
        [self.commentBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.shareBtn.mas_centerY);
            make.width.height.mas_equalTo(self.shareBtn);
            make.right.equalTo(self.likeBtn.mas_left);
        }];
        
        [self.likeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.commentBtn.mas_centerY);
            make.width.height.equalTo(self.commentBtn);
            make.right.equalTo(self.bottomView.mas_right);
        }];
        
        [self.leftSeperateLine mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.bottomView.mas_left).offset(kScreenWidth / 3.0);
            make.size.mas_equalTo(CGSizeMake(1, 18));
            make.centerY.equalTo(self.shareBtn);
        }];
        
        [self.rightSeperateLine mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.centerY.equalTo(self.leftSeperateLine);
            make.right.equalTo(self.bottomView.mas_right).offset(-kScreenWidth / 3.0);
        }];
        
        
        [self.commentBtn setTitle:@"评论" forState:UIControlStateNormal];
        [self.commentBtn setImage:[UIImage imageNamed:@"comment_cell_comment"] forState:UIControlStateNormal];
    }else{
        
        self.likeBtn.hidden = YES;
        self.leftSeperateLine.hidden = NO;
        self.rightSeperateLine.hidden = YES;
        
        [self.shareBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.equalTo(self.bottomView);
            make.top.equalTo(self.bottomHintView.mas_bottom);
            make.right.equalTo(self.commentBtn.mas_left);
        }];
        
        [self.commentBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.shareBtn.mas_centerY);
            make.width.height.mas_equalTo(self.shareBtn);
            make.right.equalTo(self.bottomView.mas_right);
        }];
        
        [self.leftSeperateLine mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.bottomView.mas_left).offset(kScreenWidth / 2.0);
            make.size.mas_equalTo(CGSizeMake(1, 18));
            make.centerY.equalTo(self.shareBtn);
        }];
        
        [self.commentBtn setTitle:@"帮助他" forState:UIControlStateNormal];
        [self.commentBtn setImage:[UIImage imageNamed:@"pencel_icon"] forState:UIControlStateNormal];
    }
    
}


#pragma mark- public methods

+ (void)createImageViewsForView:(UIView *)imagesView
                     byPostData:(FeedModel *)postData{
    CGFloat imgheight = [FeedTableViewCell oneLineImageHeight:postData.images];
    NSUInteger count = postData.images.count;
    NSArray *imgs = postData.images;
    
    [imgs enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        @autoreleasepool {
            
            UIImageView *imgv = [UIImageView new];
            imgv.backgroundColor = RGB(245, 245, 245);
            imgv.tag = idx;
            [imgv setContentMode:UIViewContentModeScaleAspectFill];
            imgv.clipsToBounds = YES;
            [imagesView addSubview:imgv];
            
            CGFloat leftOffset = idx%3*imgheight + kImageViewPadding*(idx%3);
            
            CGFloat topOffset = (idx/3)*imgheight + kImageViewPadding*(idx/3);
            
            if (count == 4) {
                if (idx == 2) {
                    leftOffset = 0;
                    topOffset = imgheight + kImageViewPadding;
                }else if (idx == 3){
                    leftOffset = imgheight + kImageViewPadding;
                }
            }
            
            [imgv mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(imagesView).offset(leftOffset);
                make.top.equalTo(imagesView).offset(topOffset);
                make.size.mas_equalTo(CGSizeMake(imgheight, imgheight));
            }];
        }
    }];
}

/** 一行图片高度  */
+ (CGFloat)oneLineImageHeight:(NSArray *)images {
    
    if (images.count < 5) {
        if(images.count == 1){
            return kScreenWidth;
            
        }else if(images.count == 4){
            return (kScreenWidth - kImageViewPadding) / 2;
            
        }else{
            return (kScreenWidth - kImageViewPadding * (images.count - 1))/images.count;
        }
    }else{
        return (kScreenWidth - kImageViewPadding * 2 - kSummaryPadding_Left * 2)/3;
    }
}

/** 图片容器高度  */
+ (CGFloat)heightForImages:(NSArray *)images {
    if(images.count == 0) return 0;
    
    if(images.count == 1){
        return kScreenWidth;
        
    }else if(images.count == 2 || images.count == 4){
        CGFloat oneLineHeight = (kScreenWidth - kImageViewPadding)/2;
        return oneLineHeight*(images.count/2)+((images.count/2)-1)*kImageViewPadding; // 图片高度*行数 + 中间间距
        
    }else if(images.count == 3){
        return (kScreenWidth - kImageViewPadding)/3;
        
    }else{
        CGFloat oneLineHeight = (kScreenWidth-kSinkMargin_Left*2-kContainerMargin_Left*2 - kImageViewPadding*2-kSummaryPadding_Left * 2)/3;
        NSUInteger lines = images.count/3 + (images.count%3>0?1:0);
        return oneLineHeight * lines + kImageViewPadding * (lines - 1);
    }
    
}

@end
